package de.nak.fireDepartment.administrationAction;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.LookupDispatchActionSupport;

import de.nak.fireDepartment.actionForms.EquipmentForm;
import de.nak.fireDepartment.exceptions.ErrorOnDeleteException;
import de.nak.fireDepartment.model.Car;
import de.nak.fireDepartment.model.Equipment;
import de.nak.fireDepartment.service.CarService;
import de.nak.fireDepartment.service.EquipmentService;
import de.nak.fireDepartment.service.ImageUploadService;
import de.nak.fireDepartment.service.LoginService;

/**
 * Action that works with a selected equipment
 * 
 * @author Nils Bredow
 */
public class EquipmentAction extends LookupDispatchActionSupport {

	/**
	 * This method shows the selected equipment into the equipmentForm
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward showEquipment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => EquipmentForm
		EquipmentForm equipmentForm = (EquipmentForm) form;
		EquipmentService equipmentService = (EquipmentService) getWebApplicationContext().getBean("equipmentService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// if no line selected display error
		if(equipmentForm.getSelectedKey()==null){
			equipmentForm.setErrorCode("text.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get equipment
		Equipment equipment = equipmentService.showEquipment(equipmentForm.getSelectedKey());
		
		// if equipment has no image set default image
		if (equipment.getImageURL() == null || equipment.getImageURL().equals("")){
			equipment.setImageURL("/FireDepartmentManagement/images/layout/noImage.jpg");
		}
		
		// store equipment in form
		equipmentForm.setEquipment(equipment);		
		// Return result
		return mapping.findForward("show");
	}
	
	/**
	 * This method prepares to create an equipment
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward createEquipment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => EquipmentForm
		EquipmentForm equipmentForm = (EquipmentForm) form;
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		
		// validate the user-login
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// create new EquipmentObject
		Equipment equipment = new Equipment();
		// store values in equipmentForm
		equipmentForm.setEquipment(equipment);
		equipmentForm.setSelectedCarNames(new LinkedList<String>());
		equipmentForm.setErrorCode("");		
		// Return result
		return mapping.findForward("create");
	}
	
	/**
	 * This method prepares to edit a equipment
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward editEquipment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => EquipmentForm
		EquipmentForm equipmentForm = (EquipmentForm) form;
		EquipmentService equipmentService = (EquipmentService)getWebApplicationContext().getBean("equipmentService");
		CarService carService = (CarService) getWebApplicationContext().getBean("carService");
		
		// Validates the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// if no line selected display error
		if(equipmentForm.getSelectedKey()==null){
			equipmentForm.setErrorCode("text.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get available cars
		Collection<Car> cars = carService.listCars();
		// get selected equipment
		Equipment equipment = equipmentService.showEquipment(equipmentForm.getSelectedKey());
		// get cars pf equipment
		Collection<Car> carsOfEquipment = equipment.getCars();
		
		//Iterate over all Cars to get the Cars of the Department for the selectionlist
		int i = 0;
		Collection <String> selectedCarNames = new LinkedList<String>();
		for (Car car : cars) {
			for (Car carOfEquipment : carsOfEquipment) {
				if(car.equals(carOfEquipment)){
					selectedCarNames.add(car.getModelName());
					i++;
				}
			}
		}
		
		// store values in equipmentForm
		equipmentForm.setSelectedCarNames(selectedCarNames);
		equipmentForm.setEquipment(equipment);
		equipmentForm.setErrorCode("");	
		// Return result
		return mapping.findForward("edit");
	}
	
	/**
	 * This method deletes the selected equipment
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward deleteEquipment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => EquipmentForm
		EquipmentForm equipmentForm = (EquipmentForm) form;
		EquipmentService equipmentService = (EquipmentService)getWebApplicationContext().getBean("equipmentService");
		ImageUploadService imageUploadService = (ImageUploadService)getWebApplicationContext().getBean("imageUploadService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// if no line selected display error
		if(equipmentForm.getSelectedKey()==null){
			equipmentForm.setErrorCode("text.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get the selected equipment
		Equipment equip = equipmentService.showEquipment(equipmentForm.getSelectedKey());
		String imageURL = equip.getImageURL();
		try{
			// delete the equipment
			equipmentService.deleteEquipment(equipmentForm.getSelectedKey());
			// delete the linked image of the equipment
			imageUploadService.deleteImage(imageURL, getServletContext());
			// get the available list of equipments and store values in form
			equipmentForm.setEquipments(equipmentService.listEquipments());
			equipmentForm.setErrorCode("");
		}catch(ErrorOnDeleteException ex){
			equipmentForm.setErrorCode(ex.getMessage());
		}
		// Return result
		return mapping.findForward("success");
	}
	
	/** {@inheritDoc} */
	@Override
	protected Map<String, String> getKeyMethodMap() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("button.show", "showEquipment");
		map.put("button.edit", "editEquipment");
		map.put("button.create", "createEquipment");
		map.put("button.delete", "deleteEquipment");
		return map;
	}
}
